#include "rtconfig.h"
#include "rtthread.h"
#include <rtdevice.h>
#include "finsh.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define GT1151Q_DEVICE_ADDR    0x28
static uint8_t dev_addr[2] = {0x81, 0x40};

static rt_err_t write_data(struct rt_i2c_bus_device *bus, uint16_t addr, uint8_t *data, int data_size)
{
    struct rt_i2c_msg msgs;
    msgs.addr = addr;
    msgs.buf = data;
    msgs.len = data_size;
    msgs.flags = RT_I2C_WR;

    if (rt_i2c_transfer(bus, &msgs, 1) == 1)
    {
        return RT_EOK;
    }
    else
    {
        return -RT_ERROR;
    }
}

static rt_err_t read_data(struct rt_i2c_bus_device *bus, uint16_t addr, uint8_t *data, int data_size)
{
    struct rt_i2c_msg msgs;
    msgs.addr = addr;
    msgs.buf = data;
    msgs.len = data_size;
    msgs.flags = RT_I2C_RD;

    if (rt_i2c_transfer(bus, &msgs, 1) == 1)
    {
        return RT_EOK;
    }
    else
    {
        return -RT_ERROR;
    }
}

static void i2ctest(int argc, char **args)
{
   rt_device_t dev = rt_device_find("i2c0");
   if(dev == NULL)
   {
        printf("Invalid i2c0 bus device\r\n");
        return;
   }

    struct rt_i2c_bus_device *i2cbus0 = (struct rt_i2c_bus_device *)dev;
    for(int i=0; i<100; i++)
    {
        uint8_t buffer[5] = {0};
        write_data(i2cbus0, GT1151Q_DEVICE_ADDR, dev_addr, 2);
        read_data(i2cbus0, GT1151Q_DEVICE_ADDR, buffer, 4);
        printf("touch id: %s\r\n", buffer);
        rt_thread_delay(100);
    }

}


MSH_CMD_EXPORT_ALIAS(i2ctest, i2ctest, This is a i2c bus test!);
